package org.epidroid.epidroid.androsoul.engine.communication;

import java.util.LinkedList;
import java.util.Queue;

import org.epidroid.epidroid.androsoul.exceptions.AndroSoulException;

public class QueryQueue {

	public Connection _connection;
	private Queue<Query> _queue;

	public QueryQueue(Connection connection) {
		_queue = new LinkedList<Query>();
		_connection = connection;
	}

	public Queue<Query> getQueue() {
		return _queue;
	}

	public void push(Query q) throws AndroSoulException {
		synchronized (_queue) {
			if (_queue.isEmpty()) {
				if (q.needResp())
					_queue.add(q);
				_connection.Query(q.getContent());
			} else if (q.needResp())
				_queue.add(q);
			else
				_connection.Query(q.getContent());
		}
	}

	/**
	 * @throws AndroSoulException
	 */
	public void poll() throws AndroSoulException {
		synchronized (_queue) {
			_queue.poll();

			// if there is a query left, send it
			if (!_queue.isEmpty()) {
				Query q = _queue.peek();
				_connection.Query(q.getContent());
				// If the query does not need a response, delete it
				if (!q.needResp())
					poll();
			}
		}
	}

	public void clear() {
		_queue.clear();
	}

}
